package org.example.day10;

/**
 * 3.3.1 ThreadLocal的使用
 *      解决线程之间变量的隔离性
 *      每个线程都能在t1中set数据，且都只获取本线程set进去的数据。
 */
public class MyThread {
    public static ThreadLocal t1 = new ThreadLocal();

    public static void main(String[] args) {
        try {
            Thread1A ta = new Thread1A();
            Thread1B tb = new Thread1B();
            ta.start();
            tb.start();
            for (int i = 0; i < 100; i++) {
                MyThread.t1.set("main" + (i+1));
                System.out.println("Main get Value = " + MyThread.t1.get());
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread1A extends Thread{
    @Override
    public void run() {
        try {
            for (int i = 0; i < 100; i++) {
                MyThread.t1.set("ThreadA" + (i+1));
                System.out.println("ThreadA get Value = " + MyThread.t1.get());
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread1B extends Thread{
    @Override
    public void run() {
        try {
            for (int i = 0; i < 100; i++) {
                MyThread.t1.set("ThreadB" + (i+1));
                System.out.println("ThreadB get Value = " + MyThread.t1.get());
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}